import { IBreadcrumb } from '@/base-ui/nav-breadcrumb'
import { RouteRecordRaw } from 'vue-router'

let firstMenu: any = null
export function mapMenusToRoutes(UserMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  //加载所有的界面
  const allRoutes: RouteRecordRaw[] = []
  const routesFiles = require.context('../router/main', true, /\.ts/)
  routesFiles.keys().forEach((kes) => {
    const route = require('@/router/main' + kes.split('.')[1])
    allRoutes.push(route.default)
  })

  //定义一个递归函数 要求传一个值(就是登录获取的用户菜单 里面有对应的path)
  const _recurseGetRouter = (menus: any) => {
    for (const menu of menus) {
      //判断是否为2级菜单
      if (menu.type === 2) {
        //判断所有路由对象里是否有用户菜单对应的路径
        const route = allRoutes.find((route) => route.path == menu.url)
        // console.log(route)

        if (route) {
          routes.push(route)
        }
        //保存第一个遍历的二级菜单
        if (!firstMenu) {
          firstMenu = menu
        }
      } else {
        //递归操作在调用这个函数传入他的children
        _recurseGetRouter(menu.children)
      }
    }
  }
  _recurseGetRouter(UserMenus)

  return routes
}

//面包屑
export function pathMapBreadcrumbs(usemenus: any[], path: string): any {
  const Breadcrumbs: IBreadcrumb[] = []
  pathmapTomenu(usemenus, path, Breadcrumbs)
  return Breadcrumbs
}

//usemenus
export function pathmapTomenu(
  usemenus: any[],
  path: string,
  Breadcrumbs?: IBreadcrumb[]
): any {
  for (const routes of usemenus) {
    if (routes.type === 1) {
      const findMenu = pathmapTomenu(routes.children ?? [], path)
      if (findMenu) {
        //保存面包屑要用的路径
        Breadcrumbs?.push({ name: routes.name, path: routes.url })
        Breadcrumbs?.push({ name: findMenu.name, path: findMenu.url })
        //拿到的是当前路径匹配的路由对象
        return findMenu
      }
    } else if (routes.type === 2 && routes.url === path) {
      return routes
    }
  }
}

export { firstMenu }
